import json

import requests
from twisted.python.util import println


def main():
    t = open("推广记录瘦身.txt", "r", encoding="utf-8")
    println(t.read())
    t.close()

    f = None
    ## 文件不存在时，异常处理
    try:
        f = open("tuanzhag.txt", "r", encoding="utf-8")
        println(f.read())
    except FileNotFoundError:
        println("文件不存在")
    except LookupError:
        println("制定了未知编码")
    finally:
        if f:
            f.close()

    ##按行读取
    with open("推广记录瘦身.txt") as f:
        lines = f.readlines()
        print(lines)

    print(lines)

    ##文件写入
    text_io = open("推广记录瘦身.txt", "w", encoding="utf-8")
    text_io.write("3wsgdshgdhsgdsgdhsgdhsgd\n")


    ##Json文件处理
    mydict = {
        'name': '骆昊',
        'age': 38,
        'qq': 957658,
        'friends': ['王大锤', '白元芳'],
        'cars': [
            {'brand': 'BYD', 'max_speed': 180},
            {'brand': 'Audi', 'max_speed': 280},
            {'brand': 'Benz', 'max_speed': 320}
        ]
    }

    json.dump(mydict, text_io)
    text_io.close()

    resp = requests.get('http://api.tianapi.com/guonei/?key=APIKey&num=10')
    print(resp.text)
    load = json.loads(resp.text)
    println(load["code"])


if __name__ == '__main__':
    main()